# 1.按照要求，使用mnist数据集完成cnn处理（每题10分）
from keras.datasets import mnist
from keras import Sequential, layers, activations, optimizers, losses

# ①获取数据
# 1)获取数据信息
# 2)切分数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 3)对数据进行预处理工作
x_train = x_train.reshape(-1, 28, 28, 1) / 255
x_test = x_test.reshape(-1, 28, 28, 1) / 255
print()
# ②模型处理
# 1)创建模型
# 2)做两次卷积，卷积核尺寸3*3，卷积核大小32，使用relu激活
# 3)配合最大池化，池化和2*2
# 4)设计随机失活比例0.25
# 5)将维度展开
# 6)创建两个全连接层，神经元数量分别为128,10
model = Sequential([
    layers.Conv2D(filters=32, kernel_size=[3, 3], activation=activations.relu),
    layers.MaxPool2D(strides=[2, 2]),
    layers.Conv2D(filters=32, kernel_size=[3, 3], activation=activations.relu),
    layers.MaxPool2D(strides=[2, 2]),
    layers.Dropout(rate=0.25),
    layers.Flatten(),
    layers.Dense(units=128, activation=activations.relu),
    layers.Dense(units=10, activation=activations.softmax)
])

model.compile(optimizer=optimizers.Adam(), loss=losses.sparse_categorical_crossentropy, metrics='acc')
# 7)设置合理训练次数，保证测试集准确率高于80%
model.fit(x=x_train, y=y_train, batch_size=100, epochs=10)

model.evaluate(x=x_test, y=y_test)
